package codepulse.blogmoon.cn.system.controller;

import codepulse.blogmoon.cn.common.context.Context;
import codepulse.blogmoon.cn.common.entity.Result;
import codepulse.blogmoon.cn.common.utils.BaseConvert;
import codepulse.blogmoon.cn.system.dto.SysMenuTreeDTO;
import codepulse.blogmoon.cn.system.dto.admin.SysAdminMenuTreeDTO;
import codepulse.blogmoon.cn.system.entity.SysMenu;
import codepulse.blogmoon.cn.system.enums.MenuTypeEnum;
import codepulse.blogmoon.cn.system.service.SysMenuService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@RestController
@RequestMapping("/menu")
public class MenuController {

    @Resource
    private SysMenuService sysMenuService;

    @GetMapping("/all-tree")
    public Result getAllMenuTree() {
        return Result.success(sysMenuService.getAllMenuTree());
    }

    @GetMapping("/tree")
    public Result getTree() {
        return Result.success(sysMenuService.getMenuTree(Context.get().getBizAcctId()));
    }

    @GetMapping("/detail/{id}")
    public Result<SysMenuTreeDTO> detail(@PathVariable("id") Long id) {
        return Result.success(BaseConvert.convert(sysMenuService.getById(id), SysMenuTreeDTO.class));
    }

    @PostMapping("/create")
    public Result create(@RequestBody SysMenuTreeDTO dto) {
        SysMenu sysMenu = BaseConvert.convert(dto, SysMenu.class);
        if (Objects.equals(sysMenu.getType(), MenuTypeEnum.MENU_GROUP.getCode())) {
            sysMenu.setComponent("Layout");
        }
        sysMenu.setCreateField();
        sysMenuService.save(sysMenu);
        return Result.success();

    }

    @PostMapping("/modify")
    public Result modify(@RequestBody SysMenuTreeDTO dto) {
        SysMenu sysMenu = BaseConvert.convert(dto, SysMenu.class);
        sysMenu.setModifyField();
        sysMenuService.updateById(sysMenu);
        return Result.success();

    }


    @DeleteMapping("/{id}")
    public Result remove(@PathVariable("id") Long id) {
        sysMenuService.removeById(id);
        return Result.success();
    }

}
